import React, { useRef, useState } from 'react';
import { Row, Button, Radio } from 'antd';
import get from 'lodash/get';
import { useDeepCompareEffect } from 'ahooks';
import styles from '../styles.less';
import { MODES } from '@/pages/Transformer/components/TargetPanel/ConfigPanel';
import AdvancedForString from './AdvancedForString';
import BasicForString, { getRuleConfigs } from './BasicForString';
import { ALWAYS_TRUE_CONDITION, CONDITION_TRUE } from '@/pages/Transformer/settings';

function ForString({ nodePath, parent, current, dispatch, close, filter }) {
  const [mode, setMode] = useState('basic');

  useDeepCompareEffect(() => {
    const { rules } = current;

    const isBasic =
      rules === undefined ||
      rules.length === 0 ||
      (rules.length === 1 && get(rules, '[0].condition.type') === CONDITION_TRUE);

    // 默认值为`简洁`模式
    const mode = isBasic ? 'basic' : 'advanced';
    setMode(mode);
  }, [current]);

  const { rules: oldRules = [] } = current;
  const [rules, setRules] = useState(oldRules);

  const handleSave = () => {
    dispatch({
      type: 'update_node_rules_attr',
      payload: {
        nodePath,
        current,
        rules,
      },
    });

    close();
  };

  const advancedRef = useRef(null);

  return (
    <>
      <Row className="margin-bottom">
        <Radio.Group
          value={mode}
          buttonStyle="solid"
          className="margin-z"
          style={{ display: 'block' }}
          onChange={e => setMode(e.target.value)}
        >
          {MODES.map(k => (
            <Radio.Button key={k.value} value={k.value}>
              {k.title}
            </Radio.Button>
          ))}
        </Radio.Group>
      </Row>

      <div style={{ display: mode === 'basic' ? '' : 'none' }}>
        <BasicForString
          node={current}
          filter={filter}
          value={getRuleConfigs(rules)}
          onChange={config => setRules([{ condition: ALWAYS_TRUE_CONDITION, config }])}
        />
      </div>
      <div style={{ display: mode === 'advanced' ? '' : 'none' }}>
        <AdvancedForString
          node={current}
          filter={filter}
          ref={advancedRef}
          value={rules}
          onChange={setRules}
        />
      </div>

      <div className={styles.advFooter}>
        <div className="pull-left">
          {mode === 'advanced' && (
            <Button
              icon="plus"
              type="link"
              style={{ padding: 0 }}
              onClick={() => {
                advancedRef.current && advancedRef.current.addRule();
              }}
            >
              添加一组规则
            </Button>
          )}
        </div>

        <Button style={{ marginRight: 8 }} onClick={() => close(false)}>
          取消
        </Button>
        <Button type="primary" onClick={() => handleSave()}>
          保存
        </Button>
      </div>
    </>
  );
}

export default ForString;
